<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--分类数据-->
      <el-col :span="4" :xs="24">
        <div class="head-container">
          <el-input
            v-model="categoryName"
            placeholder="请输入分类名称"
            clearable
            size="small"
            prefix-icon="el-icon-search"
            style="margin-bottom: 20px"
          />
        </div>
        <div class="head-container">
          <el-tree
            :data="deptOptions"
            :props="defaultProps"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            ref="tree"
            highlight-current
            @node-click="handleNodeClick"
          />
        </div>
      </el-col>
      <!--商品属性-->
      <el-col :span="20" :xs="24">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
                 label-width="68px">
          <el-form-item label="检索" prop="name">
            <el-input
              v-model="queryParams.key"
              placeholder="请输入属性名"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
              v-hasPermi="['system:user:add']"
            >新增
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="success"
              plain
              icon="el-icon-edit"
              size="mini"
              :disabled="single"
              @click="handleUpdate"
            >修改
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="el-icon-delete"
              size="mini"
              :disabled="multiple"
              @click="handleDelete"
            >删除
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="info"
              plain
              icon="el-icon-upload2"
              size="mini"
              @click="handleImport"
              v-hasPermi="['system:user:import']"
            >导入
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="warning"
              plain
              icon="el-icon-download"
              size="mini"
              @click="handleExport"
              v-hasPermi="['system:user:export']"
            >导出
            </el-button>
          </el-col>
          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="attrList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="50" align="center"/>
          <el-table-column label="属性id" align="center" prop="id"/>
          <el-table-column label="属性名" align="center" prop="name"/>
          <el-table-column label="是否需要检索" align="center" prop="searchType">
            <template slot-scope="scope">
              <span style="margin-left: 10px">{{ scope.row.searchType === 0 ? '否' : '是' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="属性图标" align="center" prop="icon">
            <template slot-scope="scope">
              <el-popover placement="top-start" title="" trigger="hover">
                <img :src="scope.row.icon" alt="" style="width: 150px;height: 150px">
                <img slot="reference" :src="scope.row.icon" style="width: 30px;height: 30px">
              </el-popover>
            </template>
          </el-table-column>
          <el-table-column label="可选值列表" align="center" prop="valueSelect"/>
          <el-table-column
            prop="tag"
            label="属性类型"
            width="115"
            :filters="[{ text: '销售属性', value: 0 }, { text: '基本属性', value: 1 },{ text: '销售和基本属性', value: 2 }]"
            :filter-method="filterTag"
            filter-placement="bottom-end">
            <template slot-scope="scope">
              <el-tag
                :type="scope.row.type === 0 ? 'primary' : (scope.row.type === 1 ? 'success':'info')"
                disable-transitions>{{ scope.row.type === 0 ? '销售属性' : (scope.row.type === 1 ? '基础属性' : '销售和基础属性') }}
              </el-tag>
            </template>
          </el-table-column>

          <el-table-column label="启用状态" align="center" prop="enable">
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.enable"
                active-color="#13ce66"
                inactive-color="#ff4949"
                active-value="0"
                inactive-value="1"
                @change="handleStatusChange(scope.row)"
              ></el-switch>
            </template>
          </el-table-column>

          <el-table-column label="快速展示" align="center" prop="showDesc">
            <template slot-scope="scope">
              <span style="margin-left: 10px">{{ scope.row.showDesc === 0 ? '否' : '是' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="所属分类" align="center" prop="categoryName"/>
          <el-table-column label="规格" align="center" prop="groupName">
          </el-table-column>
          <el-table-column
            fixed="right"
            label="操作"
            align="center"
            width="80px"
            class-name="small-padding fixed-width"
          >
            <template slot-scope="scope" v-if="scope.row.userId !== 1">
              <el-button @click="handleUpdate(scope.row)" type="text" size="small">编辑</el-button>
              <el-button @click="handleDelete(scope.row)" type="text" size="small">删除</el-button>

              <el-dropdown size="mini" @command="(command) => handleCommand(command, scope.row)">
                <span class="el-dropdown-link">
                  <i class="el-icon-d-arrow-right el-icon--right"></i>更多
                </span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item command="handleUpdate" icon="el-icon-key"
                  >修改
                  </el-dropdown-item>
                  <el-dropdown-item command="handleDelete" icon="el-icon-circle-check"
                  >删除
                  </el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </el-col>
    </el-row>

    <!-- 添加或修改用户配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="属性名" prop="name">
          <el-input v-model="form.name" placeholder="请输入属性名"/>
        </el-form-item>

        <el-form-item label="属性类型" prop="icon">
          <el-input v-model="form.type" placeholder="请输入属性类型"/>
        </el-form-item>
        <el-form-item label="属性图标" prop="icon">
          <el-input v-model="form.icon" placeholder="请输入属性图标"/>
        </el-form-item>
        <el-form-item label="可选值列表[用逗号分隔]" prop="valueSelect">
          <el-input v-model="form.valueSelect" placeholder="请输入可选值列表[用逗号分隔]"/>
        </el-form-item>
        <el-form-item label="启用状态" prop="enable">
          <el-input v-model="form.enable" placeholder="请输入启用状态"/>
        </el-form-item>
        <el-form-item label="快速展示" prop="showDesc">
          <el-input v-model="form.showDesc" placeholder="请输入快速展示"/>
        </el-form-item>
        <el-form-item label="所属分类" prop="categoryId">
          <el-cascader
            filterable
            clearable
            v-model="values"
            :options="categoryList"
            :props="props"
            @change="handleChange"></el-cascader>
        </el-form-item>
        <el-form-item label="规格分组" prop="groupId">
          <el-select v-model="form.groupId" placeholder="请选择规格分组">
            <el-option
              v-for="item in groupList"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 用户导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport"/>
            是否更新已经存在的用户数据
          </div>
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;"
                   @click="importTemplate">下载模板
          </el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {listGroup} from "@/api/product/group";
import {listAttr, getAttr, delAttr, updateAttr, addAttr, attrChangeStatus} from "@/api/product/attr";
import {getToken} from "@/utils/auth";
import {listCategory} from "@/api/product/category";

import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "Attr",
  components: {Treeselect},
  data() {
    return {
      props: {
        value: "id",
        label: "label",
        children: "children"
      },
      //级联选择器  当前选中的值
      values: [],
      //级联选择器 分类数据
      categoryList: [],
      //分组数据
      groupList: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户表格数据
      userList: null,

      // 属性表格数据
      attrList: null,
      // 弹出层标题
      title: "",
      // 部门树选项
      deptOptions: undefined,
      // 是否显示弹出层
      open: false,
      // 部门名称
      deptName: undefined,
      //分类名称
      categoryName: undefined,
      // 日期范围
      dateRange: [],
      // 表单参数
      form: {},
      defaultProps: {
        children: "children",
        label: "label"
      },
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: {Authorization: "Bearer " + getToken()},
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/system/user/importData"
      },
      // 查询参数
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        searchType: null,
        icon: null,
        valueSelect: null,
        type: null,
        enable: null,
        showDesc: null,
        categoryId: 0,
        groupId: null,
        key: "",
      },
      // 表单校验
      rules: {}
    };
  },
  watch: {

    // 根据名称筛选部门树
    categoryName(val) {
      this.$refs.tree.filter(val);
    }
  },
  created() {
    this.getList();
    this.getTreeselect();
    this.getGroup();
  },
  methods: {
    getGroup() {
      let data = {categoryId: 0, key: ""}
      listGroup(data).then(response => {
          this.groupList = response.rows;
        }
      );
    },
    //级联选择单击事件
    handleChange(value) {
      this.form.categoryId = value[value.length - 1]
      console.log(value);
    },
    /**
     * 属性类型
     * @param value
     * @param row
     * @returns {boolean}
     */
    filterTag(value, row) {
      console.log(value)
      return row.type === value;
    },
    /** 查询商品规格 */
    getList() {
      this.loading = true;
      listAttr(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
          this.attrList = response.rows;
          this.total = response.total;
          this.loading = false;
        }
      );
    },
    /** 查询部门下拉树结构 */
    getTreeselect() {
      listCategory().then(response => {
        this.deptOptions = response.data;
        this.categoryList = response.data;
      });
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.categoryId = data.id;
      this.handleQuery();
    },
    // 商品规格状态修改
    handleStatusChange(row) {
      let text = row.enable === "0" ? "启用" : "停用";
      this.$modal.confirm('确认要"' + text + '""' + row.name + '"用户吗？').then(function () {
        return attrChangeStatus(row.id, row.enable);
      }).then(() => {
        this.$modal.msgSuccess(text + "成功");
      }).catch(function () {
        row.enable = row.enable === "0" ? "1" : "0";
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.values=[];
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {};
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.queryParams.categoryId = undefined
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    // 更多操作触发
    handleCommand(command, row) {
      switch (command) {
        case "handleUpdate":
          this.handleUpdate(row);
          break;
        case "handleDelete":
          this.handleDelete(row);
          break;
        default:
          break;
      }
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.getTreeselect();
      this.open = true;
      this.title = "添加用户";

    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.getTreeselect();
      const id = row.id || this.ids;
      getAttr(id).then(response => {
        this.form = response.data;
        this.values = response.data.categoryPath
        this.open = true;
        this.title = "修改用户";
      });
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != undefined) {
            updateAttr(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addAttr(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const userIds = row.id || this.ids;
      this.$modal.confirm('是否确认删除用户编号为"' + userIds + '"的数据项？').then(function () {
        return delAttr(userIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/user/export', {
        ...this.queryParams
      }, `user_${new Date().getTime()}.xlsx`)
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "用户导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download('system/user/importTemplate', {}, `user_template_${new Date().getTime()}.xlsx`)
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", {dangerouslyUseHTMLString: true});
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    }
  }
};
</script>
